/**
 * @projectName: petJoyHome
 * @author: 小飞
 * @description: TODO
 * @date: 2024/3/1 16:30
 * @version: 1.0
 */
package com.home.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
public class LoginUser implements UserDetails {
    private User user;
    private List<String> permissions;
    //为了更加方便就把它定义为成员变量方便直接用，不用每次调用都创建
    //表示不将这个成员变量序列化放到redis中
    // 第一是因为redis序列化SimpleGrantedAuthority对象会报错
    // 第二是没必要,因为在前面的permissions里面就存的是权限信息
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    public LoginUser() {

    }

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //因为会涉及到多次调用所以这里判断成员变量是否为空,不用每次都再重新运行一遍下面的,提高效率
        if (!Objects.isNull(authorities)) {
            return authorities;
        }
        //把permissions里面放的String类型的权限信息封装成SimpleGrantedAuthority对象(下面使用函数式编程和String流)
        authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
